package com.itqf.service.impl;

import com.itqf.dao.CartDao;
import com.itqf.dao.impl.CartDaoImpl;
import com.itqf.pojo.Cart;
import com.itqf.pojo.Goods;
import com.itqf.service.CartService;
import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * projectName: gpshop
 *
 * @author: 赵伟风
 * time: 2021/7/22 20:28
 * description:
 */
public class CartServiceImpl implements CartService {

    /**
     * 添加购物车业务方法
     *
     * @param gId
     * @param gPrice
     * @param uId
     */
    @Override
    public void save(String gId, String gPrice, int uId) throws SQLException {

        CartDao cartDao = new CartDaoImpl();
        //1.判断是否存在商品!
        Cart cart =  cartDao.check(uId,gId);
        //2.确定是添加还是修改
        if (cart != null) {
            //修改了
            cart.setcNumber(cart.getcNumber()+1);
            cart.setcTotal(cart.getcTotal()+Integer.parseInt(gPrice));
            //修改购物车
            cartDao.updateCart(cart);
        }else{
            //添加购物车
            //新构建对象
            cart = new Cart();

            cart.setuId(uId);
            cart.setgId(Integer.parseInt(gId));
            cart.setcNumber(1); //初始化是1
            cart.setcTotal(Integer.parseInt(gPrice));
            cartDao.insertCart(cart);
        }

    }

    /**
     * 购物车数据查询
     *
     * @param uId
     * @return
     */
    @Override
    public List<Cart> findAll(int uId) throws InvocationTargetException, IllegalAccessException, SQLException {

        CartDao cartDao = new CartDaoImpl();
        //查询的数据返回是list<map>
        //map包含的是一行数据!
        //手动封装结果集
       List<Map<String,Object>> mapList =  cartDao.queryAll(uId);

       List<Cart> cartList = new ArrayList<>();

        for (Map<String, Object> map : mapList) {
            Cart cart = new Cart();
            Goods goods = new Goods();

            BeanUtils.populate(cart, map);
            BeanUtils.populate(goods, map);
            goods.setcId((Integer) map.get("tId"));

            cart.setGoods(goods);
            //查询的商品数据添加到购物车
            cartList.add(cart);
        }

        return cartList;
    }
}
